<template>
  <div class="px-5 md:px-20 space-y-3 py-10">
    <div class="flex justify-between space-x-1">
      <div class="flex space-x-3">
        <FileUploadButton @handleUploadSuccess="searchFolderList"></FileUploadButton>
        <n-button @click="handleNewFolder" size="large">
          <TextIcon class="hidden md:block" icon="ant-design:folder-add-outlined" :icon-size="25">新建文件夹</TextIcon>
          <TextIcon class="md:hidden" icon="ant-design:folder-add-outlined" :icon-size="25" tip="新建文件夹"></TextIcon>
        </n-button>
      </div>
      <div>
        <n-input v-model:value="keyword" clearable size="large" placeholder="搜索全部文件"
                 @keydown.enter="searchFileList" @clear="getList">
          <template #prefix>
            <TextIcon icon="ant-design:search-outline" :icon-size="20"></TextIcon>
          </template>
        </n-input>
      </div>
    </div>
    <div class="flex items-center justify-between ">
      <div class="flex  items-center  space-x-1">
        <n-button @click="handleHomeFolder" secondary>
          <TextIcon class="hidden md:block" icon="carbon:home" :icon-size="25">全部文件</TextIcon>
          <TextIcon class="md:hidden" icon="carbon:home" :icon-size="25" tip="全部文件"></TextIcon>
        </n-button>
        <span v-if="pathName" class="text-gray-400"> /</span>
        <n-breadcrumb v-if="pathName">
          <n-breadcrumb-item @click="handleBreadcrumb(index+1)"
                             separator=">"
                             v-for="(item,index) in pathName.split('/').slice(1)"
                             :key="index">
            {{ item }}
          </n-breadcrumb-item>
        </n-breadcrumb>
      </div>
      <div class="space-x-3 flex">
        <div>
          <n-button-group>
            <n-button @click="handleDownload" v-if="selectedRowsKey.length>0">下载</n-button>
            <n-button @click="handleRename" v-if="selectedRowsKey.length===1">重命名</n-button>
            <n-button @click="handleRemove" v-if="selectedRowsKey.length>0">删除</n-button>
          </n-button-group>
        </div>
        <n-popselect v-model:value="option" :options="options" trigger="click" @update:value="handleSelect">
          <n-button circle secondary>
            <TextIcon icon="uil:filter" tip="筛选"></TextIcon>
          </n-button>
        </n-popselect>

        <n-button circle secondary @click="handleReload">
          <TextIcon icon="oi:reload" tip="刷新"></TextIcon>
        </n-button>
      </div>
    </div>
    <FileFolderTable ref="tableRef" :data="list" v-model:selected-row="selectedRowsKey"
                     @handleGetList="getList"></FileFolderTable>
    <FileUploadDragButton @handleUploadSuccess="searchFolderList"></FileUploadDragButton>
  </div>
</template>

<script setup lang="ts">
import api from "@/api";
import {onMounted, ref} from "vue";
import FileFolderTable from "@/components/table/FileFolderTable.vue";
import {useFileStore} from "@/store/file";
import {storeToRefs} from "pinia";
import dayjs from "@/utils/dayjs";

import TextIcon from "@/components/text/TextIcon.vue";
import FileUploadButton from "@/components/upload/FileUploadButton.vue";
import FileUploadDragButton from "@/components/upload/FileUploadDragButton.vue";
import {useUserStore} from "@/store/user";

const tableRef = ref()
const selectedRowsKey = ref([])
const keyword = ref('')
const fileStore = useFileStore()
const {parentId, pathName, idPath} = storeToRefs(fileStore)
const userStore = useUserStore()
const {userInfo} = storeToRefs(userStore)
const list = ref<any[]>([]);
const option = ref('默认排序')
const options = ref([{
  label: '默认排序',
  value: '默认排序',
}, {
  label: '按时间排序',
  value: '按时间排序',
}, {
  label: '按名称排序',
  value: '按名称排序',
},])

onMounted(() => {
  getList()
})

const handleHomeFolder = () => {
  parentId.value = ''
  pathName.value = ''
  idPath.value = ''
  getList()
}

const getList = () => {
  window.$loadingBar.start()
  api.folder.view({
    parentId: parentId.value,
    creatorId: userInfo.value.id,
    pathName: pathName.value + '/'
  }).then(res => {
    list.value = res.data.data.folders
    list.value = list.value.concat(res.data.data.files)
    list.value = list.value.map((item: any, index) => {
      return {...item, key: index};
    });

  }).finally(() => {
    window.$loadingBar.finish()
  })
}
const searchFileList = () => {
  parentId.value = ''
  idPath.value = ''
  pathName.value = ''
  if (keyword.value === '') {
    getList()
  } else {
    window.$loadingBar.start()
    api.file.search({
      creatorId: userInfo.value.id,
      searchKey: keyword.value
    }).then(res => {
      list.value = res.data.data
      list.value = list.value.map((item: any, index) => {
        return {...item, key: index};
      });
    }).finally(() => {
      window.$loadingBar.finish()
    })

  }
}
/**
 * 插件文件夹下 所有文件和文件夹
 */
const searchFolderList = () => {
  window.$loadingBar.start()
  api.folder.search({
    creatorId: userInfo.value.id,
    parentId: parentId.value,
    searchKey: ''
  }).then(res => {
    list.value = res.data.data.folders
    list.value = list.value.concat(res.data.data.files)
    list.value = list.value.map((item: any, index) => {
      return {...item, key: index};
    });
  }).finally(() => {
    window.$loadingBar.finish()
  })
}
/**
 * 点击面包屑
 * @param index
 */
const handleBreadcrumb = (index: number) => {
  console.log(index)
  console.log(idPath.value)
  console.log(idPath.value.split('/'))
  parentId.value = String(idPath.value.split('/').at(index))
  pathName.value = pathName.value.split('/').slice(0, index + 1).join('/')
  idPath.value = idPath.value.split('/').slice(0, index + 1).join('/')
  console.log(parentId.value, pathName.value, idPath.value)
  searchFolderList()
}
/**
 * 新建文件夹
 */
const handleNewFolder = () => {
  let name = '新建文件夹-' + dayjs().format('YYYYMMDDHHmmss')
  api.folder.newFolder({
    parentId: parentId.value,
    creatorId: userInfo.value.id,
    pathName: pathName.value + '/' + name
  }).then(res => {
    if (res.data.code === 0) {
      window.$message.success('新建文件夹成功')
      getList()
    }
  })
}

const handleSelect = (option: any) => {
  console.log(option)
  if (option === '默认排序') {
    getList()
  } else if (option === '按时间排序') {
    list.value.sort((a: any, b: any) => b.updatedAt.localeCompare(a.updatedAt));
  } else if (option === '按名称排序') {
    list.value.sort((a: any, b: any) => a.name.localeCompare(b.name));
    console.log(list.value);
  }

}
const handleReload = () => {
  getList()
}

const handleDownload = () => {
  tableRef.value.doDownload()
}
const handleRemove = () => {
  tableRef.value.doRemove()
}
const handleRename = () => {
  tableRef.value.doRename()
}


</script>

<style scoped>

</style>